package com.example.chenjun.myapplication.net.netcallback;

import com.example.chenjun.myapplication.exeption.CookException;
import com.example.chenjun.myapplication.util.TypeUtil;
import com.google.gson.Gson;

import org.json.JSONObject;

import java.lang.reflect.Type;

public abstract class BaseCallback<T> implements NetCallback<T>, ParseCallback<T> {
    private JSONObject mJson;
    private static final String SUCCESS = "200";
    protected Type mType;
    protected String mResultCode;
    protected String mReason;
    protected String mErrorCode;

    @Override
    public T parse(String str) throws NullPointerException {
        mType = TypeUtil.getType(this);
        if (mType == null){
            throw new NullPointerException("type == null");
        }
        try {
            mJson = new JSONObject(str);
            mResultCode = mJson.optString("resultcode");
            mReason = mJson.optString("reason");
            mErrorCode = mJson.optString("error_code");
            if (isSuccess()){
                return this.parse(mJson);
            }
        }catch (Exception ignore){
        }
        return null;
    }

    protected abstract T parse(JSONObject json);

    protected boolean isSuccess() {
        return mJson != null && SUCCESS.equals(mResultCode);
    }
}
